package net.hn.hnms.biz.view.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.hn.hnms.biz.view.common.base.BaseController;
import net.hn.hnms.biz.view.common.domain.AjaxResult;
import net.hn.hnms.biz.view.common.domain.ResultTable;
import net.hn.hnms.biz.view.common.domain.Tablepar;
import net.hn.hnms.biz.view.domain.GoviewProject;
import net.hn.hnms.biz.view.domain.GoviewProjectData;
import net.hn.hnms.biz.view.domain.SysFile;
import net.hn.hnms.biz.view.domain.vo.GoviewProjectVo;
import net.hn.hnms.biz.view.domain.vo.SysFileVo;
import net.hn.hnms.biz.view.service.IGoviewProjectDataService;
import net.hn.hnms.biz.view.service.IGoviewProjectService;
import net.hn.hnms.biz.view.service.ISysFileService;
import net.hn.hnms.biz.view.utils.ConvertUtil;
import net.hn.hnms.sys.common.core.exception.ServiceException;
import net.hn.hnms.sys.common.core.utils.StringUtils;
import net.hn.hnms.sys.common.oss.core.OssClient;
import net.hn.hnms.sys.common.oss.entity.UploadResult;
import net.hn.hnms.sys.common.oss.factory.OssFactory;
import net.hn.hnms.sys.common.oss.properties.OssProperties;
import org.springframework.beans.BeanUtils;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author fc
 * @since 2023-04-30
 */
@Api(value = "项目管理", tags = {"项目管理"})
@RestController
@RequestMapping("/view/project")
public class ViewProjectController extends BaseController {

    @Resource
    private ISysFileService iSysFileService;

    @Resource
    private IGoviewProjectService iGoviewProjectService;

    @Resource
    private IGoviewProjectDataService iGoviewProjectDataService;


    @ApiOperation(value = "分页跳转", notes = "分页跳转")
    @PostMapping("/list")
    @ResponseBody
    public ResultTable list(@RequestBody Tablepar tablepar) {
        Page<GoviewProject> page = new Page<GoviewProject>(tablepar.getPage(), tablepar.getLimit());
        IPage<GoviewProject> iPages = iGoviewProjectService.page(page, new LambdaQueryWrapper<GoviewProject>());
        ResultTable resultTable = new ResultTable();
        resultTable.setData(iPages.getRecords());
        resultTable.setCode(200);
        resultTable.setCount(iPages.getTotal());
        resultTable.setMsg("获取成功");
        return resultTable;
    }

    /**
     * 新增保存
     *
     * @param
     * @return
     */
    //@Log(title = "项目表新增", action = "111")
    @ApiOperation(value = "新增", notes = "新增")
    @PostMapping("/create")
    @ResponseBody
    public AjaxResult add(@RequestBody GoviewProject goviewProject) {
        goviewProject.setCreateTime(DateUtil.now());
        goviewProject.setState(-1);
        boolean b = iGoviewProjectService.save(goviewProject);
        if (b) {
            return successData(200, goviewProject).put("msg", "创建成功");
        } else {
            return error();
        }
    }


    /**
     * 项目表删除
     *
     * @param ids
     * @return
     */
    //@Log(title = "项目表删除", action = "111")
    @ApiOperation(value = "删除", notes = "删除")
    @DeleteMapping("/delete")
    @ResponseBody
    public AjaxResult remove(String ids) {
        List<String> lista = ConvertUtil.toListStrArray(ids);
        Boolean b = iGoviewProjectService.removeByIds(lista);
        if (b) {
            return success();
        } else {
            return error();
        }
    }

    @ApiOperation(value = "修改保存", notes = "修改保存")
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(@RequestBody GoviewProject goviewProject) {
        Boolean b = iGoviewProjectService.updateById(goviewProject);
        if (b) {
            return success();
        }
        return error();
    }


    @ApiOperation(value = "项目重命名", notes = "项目重命名")
    @PostMapping("/rename")
    @ResponseBody
    public AjaxResult rename(@RequestBody GoviewProject goviewProject) {

        LambdaUpdateWrapper<GoviewProject> updateWrapper = new LambdaUpdateWrapper<GoviewProject>();
        updateWrapper.eq(GoviewProject::getId, goviewProject.getId());
        updateWrapper.set(GoviewProject::getProjectName, goviewProject.getProjectName());
        Boolean b = iGoviewProjectService.update(updateWrapper);
        if (b) {
            return success();
        }
        return error();
    }


    //发布/取消项目状态
    @PutMapping("/publish")
    @ResponseBody
    public AjaxResult updateVisible(@RequestBody GoviewProject goviewProject) {
        if (goviewProject.getState() == -1 || goviewProject.getState() == 1) {

            LambdaUpdateWrapper<GoviewProject> updateWrapper = new LambdaUpdateWrapper<GoviewProject>();
            updateWrapper.eq(GoviewProject::getId, goviewProject.getId());
            updateWrapper.set(GoviewProject::getState, goviewProject.getState());
            Boolean b = iGoviewProjectService.update(updateWrapper);
            if (b) {
                return success();
            }
            return error();
        }
        return error("警告非法字段");
    }


    @ApiOperation(value = "获取项目存储数据", notes = "获取项目存储数据")
    @GetMapping("/getData")
    @ResponseBody
    public AjaxResult getData(String projectId, ModelMap map) {
        GoviewProject goviewProject = iGoviewProjectService.getById(projectId);

        GoviewProjectData blogText = iGoviewProjectDataService.getProjectid(projectId);
        if (blogText != null) {
            GoviewProjectVo goviewProjectVo = new GoviewProjectVo();
            BeanUtils.copyProperties(goviewProject, goviewProjectVo);
            goviewProjectVo.setContent(blogText.getContent());
            return AjaxResult.successData(200, goviewProjectVo).put("msg", "获取成功");
        }
        return AjaxResult.successData(200, null).put("msg", "无数据");

    }


    @ApiOperation(value = "保存项目数据", notes = "保存项目数据")
    @PostMapping("/save/data")
    @ResponseBody
    public AjaxResult saveData(GoviewProjectData data) {

        GoviewProject goviewProject = iGoviewProjectService.getById(data.getProjectId());
        if (goviewProject == null) {
            return error("没有该项目ID");
        }
        GoviewProjectData goviewProjectData = iGoviewProjectDataService.getOne(new LambdaQueryWrapper<GoviewProjectData>().eq(GoviewProjectData::getProjectId, goviewProject.getId()));
        if (goviewProjectData != null) {
            data.setId(goviewProjectData.getId());
            iGoviewProjectDataService.updateById(data);
            return success("数据保存成功");
        } else {
            iGoviewProjectDataService.save(data);
            return success("数据保存成功");
        }
    }

    /**
     * 上传文件
     *
     * @param object     文件流对象
     * @return
     * @throws Exception
     */
    @PostMapping("/upload")
    public AjaxResult upload(@RequestBody MultipartFile object) throws IOException {
        String fileName = object.getOriginalFilename();
        //默认文件格式
        String suffixName = ".png";
        String mediaKey = "";
        Long filesize = object.getSize();
        //文件名字
        String fileSuffixName = "";
        if (fileName.lastIndexOf(".") != -1) {//有后缀
            suffixName = fileName.substring(fileName.lastIndexOf(".")).toLowerCase();
            mediaKey = IdUtil.fastSimpleUUID();
            fileSuffixName = mediaKey + suffixName;
        } else {//无后缀
            //取得唯一id
            //mediaKey = MD5.create().digestHex(fileName+suffixName);
            mediaKey = IdUtil.fastSimpleUUID();
            //fileSuffixName=mediaKey+suffixName;
        }
        OssClient storage = OssFactory.instance();
        OssProperties properties = storage.getProperties();
        UploadResult uploadResult;
        try {
            String suffix = StringUtils.substring(fileName, fileName.lastIndexOf("."), fileName.length());
            uploadResult = storage.uploadSuffix(object.getBytes(), suffix, object.getContentType());
        } catch (IOException e) {
            throw new ServiceException(e.getMessage());
        }

        String absolutePath = uploadResult.getUrl();
        SysFile sysFile = new SysFile();
        sysFile.setId(IdUtil.fastSimpleUUID());
        sysFile.setFileName(fileSuffixName);
        sysFile.setFileSize(Integer.parseInt(filesize + ""));
        sysFile.setFileSuffix(suffixName);
        sysFile.setCreateTime(DateUtil.formatLocalDateTime(LocalDateTime.now()));
        String filepath = DateUtil.formatDate(new Date());
        sysFile.setRelativePath(filepath);
        sysFile.setAbsolutePath(absolutePath);
        iSysFileService.saveOrUpdate(sysFile);
        SysFileVo sysFileVo = BeanUtil.copyProperties(sysFile, SysFileVo.class);
        sysFileVo.setFileurl(sysFile.getAbsolutePath());
        return successData(200, sysFileVo);
    }


    @ApiOperation(value = "获取oss地址", notes = "获取oss地址")
    @GetMapping("/getOssInfo")
    @ResponseBody
    public AjaxResult getOssInfo() {
        return success();
    }

}
